﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace XDCCManager.Network.IRC
{
	class ChatLineTokenizer
	{
		private Queue<byte> remainingData;
		private System.IO.MemoryStream tokenData;

		public ChatLineTokenizer(int capacity)
		{
			remainingData = new Queue<byte>(capacity);
			tokenData = new System.IO.MemoryStream(capacity);
		}

		public void Clear()
		{
			remainingData.Clear();
			tokenData.SetLength(0);
			tokenData.Position = 0;
		}

		public void Append(byte[] data, int length)
		{
			foreach (var value in data.Take(length))
				remainingData.Enqueue(value);
		}

		public string GetLine(System.Text.Encoding encoding)
		{
			if (!HasLineToken())
				return null;
			string line = new string(encoding.GetChars(tokenData.ToArray()));
			tokenData.SetLength(0);
			tokenData.Position = 0;
			return line;
		}

		protected bool HasLineToken()
		{
			if (remainingData.Count == 0)
				return false;
			while ((remainingData.Count > 0) && (remainingData.Peek() != '\n'))
				tokenData.WriteByte(remainingData.Dequeue());
			if ((remainingData.Count == 0) || (remainingData.Peek() != '\n'))
				return false;
			remainingData.Dequeue();
			while ((remainingData.Count > 0) && (remainingData.Peek() == '\n'))
				remainingData.Dequeue();
			return true;
		}
	}
}
